import { DatabaseAPI } from "./dbAPI.js";
import { nodes, links } from "./globalMgr.js";
import { width, height, simulation, updateGraph } from "./graphicsAPI.js";

export class NetworkAPI {
    /**
     * API 1: 添加单个节点及其连接
     * @param {string} name - 节点名称
     * @param {string} description - 节点描述
     * @param {Array<Number>} connections - 要连接的节点ID数组
     * @returns {Object} 新创建的节点对象
     */
    static async addNode(name, description = '', connections = [], x = null, y = null, desc_type = 'plain') {
    console.groupCollapsed(`[Node] Adding new node "${name}"`);
    // console.info('Connected node IDs:', connections);
    
    let nodeResult;
    try {
        nodeResult = await DatabaseAPI.addNode(
            name,
            description,
            x || Math.random() * width,
            y || Math.random() * height,
            '#4285f4',
            desc_type
        );
    } catch (e) {
        console.groupEnd();
        throw new Error(e && e.message ? e.message : '添加节点失败');
    }
    if (!nodeResult || nodeResult.status !== 'success' && !nodeResult.id) {
        console.groupEnd();
        throw new Error(nodeResult && nodeResult.message ? nodeResult.message : '添加节点失败');
    }
    const newNode = {
        id: nodeResult.id,
        name,
        description,
        desc_type: nodeResult.desc_type || 'plain',
        radius: nodeResult.radius,
        color: nodeResult.color,
        expanded: false,
        x: nodeResult.x,
        y: nodeResult.y
    };
    nodes.push(newNode);
    console.info('Node created with ID:', newNode.id);
    
    // 如果提供了连接节点ID，则在数据库中添加连接
    if (Array.isArray(connections) && connections.length > 0) {
        // console.info('Adding connections to nodes:', connections);
        for (const connId of connections) {
            try {
                await DatabaseAPI.addConnection(newNode.id, connId);
                links.push({ source: newNode.id, target: connId, weight: 1 });
                console.info(`Connection added: ${newNode.id} -> ${connId}`);
            } catch (e) {
                // 回滚：尝试移除新建节点，保证前后端一致
                try { await DatabaseAPI.removeNode(newNode.id); } catch (e2) {}
                console.groupEnd();
                console.error('Failed to add connection, rolling back node:', connId, e);
                throw new Error(e && e.message ? e.message : `连接节点${connId}失败`);
            }
        }
    }
        // 强制重新绑定数据并更新图形
        updateGraph();
        
        // 刷新所有Tagify实例的whitelist数据
        refreshAllTagifyWhitelists();
        
        console.groupEnd();
        return newNode;
    }

    /**
     * API 2: 批量添加节点
     * @param {Array<{name: string, description: string, connections: Array<number>, x?: number, y?: number}>} nodePairs
     * @returns {Array<Object>} 新创建的节点对象数组
     */
    static async addNodesBatch(nodePairs) {
        const results = [];
        for (const pair of nodePairs) {
            const newNode = await NetworkAPI.addNode(
                pair.name,
                pair.description,
                pair.connections || [],
                pair.x,
                pair.y
            );
            results.push(newNode);
        }
        return results;
    }

    /**
     * API 3: 添加连接
     * @param {Number} sourceId - 源节点ID
     * @param {Number} targetId - 目标节点ID
     * @returns {boolean} 是否成功添加
     */
    static async addConnection(sourceId, targetId) {
        // 检查节点是否存在
        const sourceExists = nodes.some(n => n.id === sourceId);
        const targetExists = nodes.some(n => n.id === targetId);
        if (!sourceExists || !targetExists) {
            console.error('Connection failed: One or both nodes not found', { sourceId, targetId });
            return false;
        }
        // 检查连接是否已存在
        const connectionExists = links.some(link =>
            (link.source === sourceId || link.source.id === sourceId) &&
            (link.target === targetId || link.target.id === targetId)
        );
        if (connectionExists) {
            console.warn('Connection already exists');
            return false;
        }
        // 数据库添加连接
        const result = await DatabaseAPI.addConnection(sourceId, targetId);
        if (!result || result.status !== 'success') {
            console.error('Failed to add connection to database:', result && result.message);
            throw new Error(result && result.message ? result.message : '添加连接失败');
        }
        // 前端内存同步
        links.push({ source: sourceId, target: targetId, weight: 1 });
        updateGraph();
        return true;
    }

    /**
     * API 4: 移除节点
     * @param {Number} nodeId - 要移除的节点ID
     * @returns {boolean} 是否成功移除
     */
    static async removeNode(nodeId) {
    console.groupCollapsed(`[API] Removing node "${nodeId}"`);
        const result = await DatabaseAPI.removeNode(nodeId);
        if (!result || result.status !== 'success') {
            console.error('Failed to remove node from database:', result && result.message);
            console.groupEnd();
            return false;
        }
        // 类型统一为字符串
        const nodeIdStr = String(nodeId);
        // 日志输出所有节点id类型
        // console.info('All node ids:', nodes.map(n => n.id), 'typeof nodeId:', typeof nodeId, 'typeof node.id:', nodes.length > 0 ? typeof nodes[0].id : 'n/a');
        const nodeIndex = nodes.findIndex(n => String(n.id) === nodeIdStr);
        if (nodeIndex !== -1) {
            // 移除与该节点相关的所有连接
            const newLinks = links.filter(link => {
                const sourceId = typeof link.source === 'object' ? String(link.source.id) : String(link.source);
                const targetId = typeof link.target === 'object' ? String(link.target.id) : String(link.target);
                return sourceId !== nodeIdStr && targetId !== nodeIdStr;
            });
            // 更新全局links变量
            links.length = 0;
            links.push(...newLinks);
            // 移除节点
            nodes.splice(nodeIndex, 1);
            // 强制重新绑定数据并更新图形
            simulation.nodes(nodes);
            simulation.force('link').links(links);
            simulation.alpha(1).restart();
            updateGraph();
            console.info(`[API] Node ${nodeIdStr} removed from nodes and links. Nodes left:`, nodes.length, 'Links left:', links.length);
            
            // 刷新所有Tagify实例的whitelist数据
            refreshAllTagifyWhitelists();
        } else {
            console.warn(`[API] Node ${nodeIdStr} not found in nodes array.`);
        }
        // 如果节点本就不存在于前端，也视为成功
        console.groupEnd();
        return true;
    }

    /**
     * API 5: 移除连接
     * @param {Number} sourceId - 源节点ID
     * @param {Number} targetId - 目标节点ID
     * @returns {boolean} 是否成功移除
     */
    static async removeConnection(sourceId, targetId) {
        // 从数据库删除连接
        const result = await DatabaseAPI.removeConnection(sourceId, targetId);
        if (!result || result.status !== 'success') {
            console.error('Failed to remove connection from database:', result && result.message);
            throw new Error(result && result.message ? result.message : '移除连接失败');
        }
        const connectionIndex = links.findIndex(link =>
            (link.source === sourceId || link.source.id === sourceId) &&
            (link.target === targetId || link.target.id === targetId)
        );
        if (connectionIndex === -1) {
            return false;
        }
        links.splice(connectionIndex, 1);
        updateGraph();
        return true;
    }

    /**
     * API 6: 更新节点描述信息
     * @param {Number} nodeId - 要更新的节点ID
     * @param {string} description - 新的描述内容
     * @param {string} desc_type - 描述类型(plain/markdown/html)
     * @returns {boolean} 是否成功更新
     */
    static async updateNodeDescription(nodeId, description, desc_type = 'plain') {
        console.groupCollapsed(`[API] Updating description for node ${nodeId}`);
        const result = await DatabaseAPI.updateNodeDescription(nodeId, description, desc_type);
        if (!result || result.status !== 'success') {
            console.error('Failed to update node description:', result && result.message);
            console.groupEnd();
            return false;
        }
        
        // 更新前端内存中的节点数据
        const nodeIndex = nodes.findIndex(n => n.id === nodeId);
        if (nodeIndex !== -1) {
            nodes[nodeIndex].description = description;
            nodes[nodeIndex].desc_type = desc_type;
            updateGraph();
        }
        console.info('Node description updated successfully');
        console.groupEnd();
        return true;
    }
}

// 将networkAPI暴露到全局作用域
window.NetworkAPI = NetworkAPI;

/**
 * 刷新所有Tagify实例的白名单数据
 */
function refreshAllTagifyWhitelists() {
    if (!window.tagifyInstances) return;
    window.tagifyInstances.forEach(({ instance }) => {
        if (instance) {
            instance.settings.whitelist = nodes
                .filter(n => n.id != null && n.id !== '')
                .map(n => ({
                    id: String(n.id),
                    name: n.name ? String(n.name) : String(n.id),
                    value: String(n.id)
                }));
        }
    });
}

// // 将API暴露给全局作用域
// window.NetworkAPI = {
//     addNode,
//     addNodesBatch,
//     addConnection,
//     removeNode,
//     removeConnection
// };